#include "window6.h"
#include <QDebug>
Window6::Window6(QWidget *parent) : QMainWindow(parent)
{
    setWindowTitle("多线程");
    setGeometry(300, 200, 600, 400);
   // threadTest();

    threadPoolTest();
}
//测试线程的使用
void Window6::threadTest(){
    startThreadBtn = new QPushButton(this);
    startThreadBtn->setGeometry(50, 100, 80, 30);
    startThreadBtn->setEnabled(true);
    startThreadBtn->setText("开启线程");

    stopThreadBtn = new QPushButton(this);
    stopThreadBtn->setGeometry(150, 100, 80, 30);
    stopThreadBtn->setEnabled(false);
    stopThreadBtn->setText("停止线程");

    QObject::connect(startThreadBtn, SIGNAL(clicked()), this, SLOT(slotStartThread()));
    QObject::connect(stopThreadBtn, SIGNAL(clicked()), this, SLOT(slotStopThread()));

}

void Window6::threadPoolTest(){
    //第一个 QProgressBar
    progressBar = new QProgressBar(this);
    progressBar->setGeometry(QRect(50,50,200,16));
    //初始值
    progressBar->setValue(0);
    //范围值
    progressBar->setRange(0,100000-1);


    //第二个 QProgressBar
    progressBar2 = new QProgressBar(this);
    progressBar2->setGeometry(QRect(50,100,200,16));
    //初始值
    progressBar2->setValue(0);
    //范围值
    progressBar2->setRange(0,100000-1);



    //实例按钮
    startButton = new QPushButton(this);
    startButton->setGeometry(QRect(260,45,80,25));
    startButton->setText("执行");

    QObject::connect(startButton,SIGNAL(clicked()),this,SLOT(startFun()));



}
//开启线程
void Window6::slotStartThread(){

    myThread = new MyThread(this);
    myThread->start(); //同一个线程对象不能启动两次
    startThreadBtn->setEnabled(false);
    stopThreadBtn->setEnabled(true);
    //线程结束后发信号，回收内存资源
    QObject::connect(myThread, SIGNAL(finished()), this, SLOT(slotDeleteThread()));
    qDebug() << "主线程id：" << QThread::currentThreadId() << "\n";
}
//停止线程
void Window6::slotStopThread(){
    myThread->closeThread();
    startThreadBtn->setEnabled(true);
    stopThreadBtn->setEnabled(false);
}
//回收线程对象资源
void Window6::slotDeleteThread(){
    delete myThread;
    myThread = nullptr;
}
//开启runnable
void Window6::startFun(){
    if(threadPool == nullptr){
        threadPool =  QThreadPool::globalInstance();
    }
    MyRunnable * r1 = new MyRunnable(progressBar2);
    QObject::connect(r1, SIGNAL(updateProcess(int)), this, SLOT(slotReceiveProcess(int)));
    threadPool->start(r1);

}

void Window6::slotReceiveProcess(int i){
    progressBar->setValue(i);
}
